/**********************************************************************************************************************************************/

//PID算法温控C语言


#include "pid.h"
#include "max31865.h"
#include<math.h>
#include<string.h>
//Ticker tiker_pwm;
double compute_temp(unsigned int adc_code,unsigned int bottom,unsigned int top);
struct PID
{
    double SetPoint ;
    // 设定目标 Desired Value
    double Proportion ;
    // 比例常数 Proportional Const
    double Integral ;
    // 积分常数 Integral Const
    double Derivative ;
    // 微分常数 Derivative Const
    double LastError ;
    // Error[-1]
    double PrevError ;
    // Error[-2]
//    double SumError ;
//    // Sums of Errors
}
;
struct PID spid ;
// PID Control Structure
double rout ;
// PID Response (Output)
double rin ;
// PID Feedback (Input)


//sbit output=P1^4;
DigitalOut output(PC_8);
unsigned char high_time,low_time,count=0 ;
//占空比调节参数
unsigned int set_temper=100 ;
double temper=0;
double current_temp_buf;

void PIDInit(struct PID *pp)
{
    memset(pp,0,sizeof(struct PID)); //PID参数初始化全部设置为0

	
}
void PIDSet(struct PID *spid_set)
{
	spid_set->SetPoint=100; 
	spid_set->Proportion=0.1;
	spid_set->Integral=0;
	spid_set->Derivative=0;
}
double PIDCalc(struct PID *sptr,double NextPoint)   //pid 处理函数
{
		register double iError, iIncpid; //当前误差  增量值 
	
		iError = sptr->SetPoint - NextPoint; //增量计算

		iIncpid = sptr->Proportion *(iError -sptr->LastError)//KP*(E[k]-E[k-1])项 
		+ sptr->Integral * iError														//+KI*E[k]项 
		+ sptr->Derivative *(iError-2*sptr->LastError+sptr->PrevError); //+KD*(E[k]-2*E[k-1]+E[k－2])项 
		//存储误差，用于下次计算 
		sptr->PrevError = sptr->LastError; 
		sptr->LastError = iError; 
		//返回增量值 
		return(iIncpid); 
	
}

/***********************************************************
温度比较处理子程序
***********************************************************/

unsigned int compare_temper(unsigned char chx)
{
	PIDBEGIN();
	rin=compute_temp((max31865_read_data(chx,0x01)<<7)+(max31865_read_data(chx,0x02)>>1),0,46);

	printf("rin %f .\n\r", rin);
  // Read Input
  rout+=PIDCalc(&spid,rin); //执行PID运算
	if(rout>1000)
		rout=1000;
	if(rout<0)
		rout=0;
	printf("rout %f .\n\r", rout);
		return rout;
}



void PIDBEGIN()
{
    high_time=50 ;
    low_time=50 ;
    PIDInit(&spid);
		PIDSet(&spid);
}

